import QQMapWX from '../../../libs/qqmap-wx-jssdk.min'
import Schema from 'async-validator'
import { reqAddAddress, reqAddressInfo, reqUpdateAddress } from '../../../api/address'

Page({
  data: {
    name: '', // 收货人
    phone: '', // 手机号码
    provinceName: '', // 省
    provinceCode: '', // 省编码
    cityName: '', // 市
    cityCode: '', // 市编码
    districtName: '', // 区
    districtCode: '', // 市编码
    address: '', // 详细地址
    fullAddress: '', // 完整地址
    isDefault: false // 是否设置为默认地址，0 不设置为默认地址，1 设置为默认地址
  },

  async saveAddrssForm() {
    const { provinceName, cityName, districtName, address, isDefault } = this.data

    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }

    const { valid } = await this.validatorAddress(params)
    if (!valid) return

    const res = this.addressId
      ? await reqUpdateAddress(params)
      : await reqAddAddress(params)

    if (res.code === 200) {
      wx.navigateBack({
        success: () => {
          wx.toast({
            title: this.addressId ? '更新收货地址成功！' : '新增收货地址成功！'
          })
        }
      })
    }
  },

  validatorAddress(params) {
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'

    const rules = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      provinceName: { required: true, message: '请选择收货人所在地区' },
      address: { required: true, message: '请输入详细地址' }
    }

    const validator = new Schema(rules)

    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },

  onAddressChange(event) {
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode, cityCode, districtCode] = event.detail.code

    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },

  async onLocation() {
    const { authSetting } = await wx.getSetting()
    const isAuth = !!authSetting['scope.userLocation']

    let locationRes

    if (!isAuth) {
      const modalRes = await wx.modal({
        title: '授权提示',
        content: '需要需要您的地理位置信息，请确认授权'
      })
      if (!modalRes) return wx.toast({ title: '您拒绝了授权' })

      const { authSetting } = await wx.openSetting()
      if (!authSetting['scope.userLocation']) return wx.toast({ title: '授权失败！' })
      try {
        locationRes = await wx.getLocation()
      } catch (err) {
        console.log(err)
      }
    } else {
      try {
        locationRes = await wx.getLocation()
      } catch (e) {
        wx.toast({ title: '您拒绝授权获取地址位置' })
      }
    }
    const { latitude, longitude, name } = locationRes

    // 使用 reverseGeocoder 方法进行逆地址解析
    this.qqmapwx.reverseGeocoder({
      location: {
        longitude,
        latitude
      },
      success: (res) => {
        // 获取省市区、省市区编码
        const { adcode, province, city, district } = res.result.ad_info

        // 获取街道、门牌 (街道、门牌 可能为空)
        const { street, street_number } = res.result.address_component

        // 获取标准地址
        const { standard_address } = res.result.formatted_addresses

        this.setData({
          // 省
          provinceName: province,
          // 如果是省，前 2 位有值，后面 4 位是 0
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),

          // 市
          cityName: city,
          // 如果是市，前 4 位有值，后面 2 位是 0
          cityCode: adcode.replace(adcode.substring(4, 6), '00'),

          // 区
          // 东莞市、中山市、儋州市、嘉峪关市 因其下无区县级
          districtName: district,
          districtCode: district && adcode,

          // 详细地址以及完整地址
          // 组织详细地址
          address: street + street_number + name,
          // 组织完整地址
          fullAddress: standard_address + name
        })
      }
    })
  },

  async showAddressInfo(id) {
    if (!id) return

    this.addressId = id

    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })

    const { data } = await reqAddressInfo(id)
    this.setData(data)
  },

  onLoad(options) {
    this.qqmapwx = new QQMapWX({
      key: 'S5CBZ-TQXCB-L73UJ-J6VJA-FXS53-JNBY3'
    })

    this.showAddressInfo(options.id)
  }
})
